<script setup>
import {ref} from 'vue';
import {User, Lock, ElementPlus, Message} from "@element-plus/icons-vue";
import {customerLoginService, customerRegisterService, userInfoService} from "@/apis/customer";
import {ElMessage} from "element-plus";
import {useTokenStore} from "@/stores/token";
import {useRouter} from "vue-router";
import useUserInfoStore from "@/stores/userInfo";
import {useCartStore} from "@/stores/shopcarStore";
const isRegister = ref(false)
const formRef = ref(null)
// 注册 ----------------------------------------------------------------------
const registerData = ref({
    username: '',
    nickname: '',
    password: '',
    rePassword: '',
    email: ''
})
// 自定义校验
const validatePass = (rule, value, callback) => {
    if (value === '') {
        callback(new Error('确认密码不能为空'))
    } else if (value !== registerData.value.password) {
        callback(new Error('两次输入密码不一致!'))
    } else {
        callback()
    }
}

const validateEmail = (rule, value, callback) => {
    if (!value) {
        callback()
    } else {
        const reg =
            /^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$/
        const email = reg.test(value)
        if (!email) {
            callback(new Error('邮箱格式如:admin@163.com'))
        } else {
            callback()
        }
    }
}
// 表单校验
const rules = {
    username: [
        {required: true, message: '请输入用户名', trigger: 'blur'},
        {min: 5, max: 16, message: '用户名长度5-16位', trigger: 'blur'}
    ],
    nickname: [
        {required: true, message: '请输入昵称', trigger: 'blur'},
        {min: 1, max: 10, message: '昵称长度1-10位', trigger: 'blur'}
    ],
    password: [
        {required: true, message: '请输入密码', trigger: 'blur'},
        {min: 5, max: 16, message: '密码长度5-16位', trigger: 'blur'}
    ],
    rePassword: [
        {validator: validatePass, trigger: 'blur'},
    ],
    email: [
        {validator: validateEmail, trigger: 'blur'}
    ]
}

const register = () => {
    formRef.value.validate(async (valid) => {
        if (valid) {
            let result = await customerRegisterService(registerData.value);
            ElMessage.success(result.code == 1 ? result.message : '注册成功，请登录');
            isRegister.value = false
        }
    })
}

// 登录 ----------------------------------------------------------------------
const loginData = ref({
    'username': '',
    'password': ''
})

const tokenStore = useTokenStore()
const userInfoStore = useUserInfoStore()
const cartStore = useCartStore()
const router = useRouter()

const login = () => {
    formRef.value.validate(async (valid) => {
        if (valid) {
            let result = await customerLoginService(loginData.value)
            ElMessage.success(result.message ? result.message : '登录成功')
            //把得到的token存储到tokenStore中
            tokenStore.setToken(result.data)
            let userInfo = await userInfoService();
            // 更新购物车
            userInfoStore.setInfo(userInfo.data);
            await cartStore.updateCart()
            await router.push('/')
        }
    })
}
// 点击注册或登录跳转后清除填写的信息
const clearRegisterData = () => {
    registerData.value = {
        username: '',
        nickname: '',
        password: '',
        rePassword: '',
        email: ''
    }
}

const clearLoginData = () => {
    loginData.value = {
        'username': '',
        'password': ''
    }
}
</script>

<template>
    <el-row class="login-page">
        <el-col :span="12" class="bg"></el-col>
        <el-col :span="6" :offset="3" class="form">
            <a class="title" href="/">欢迎来到购书网！</a>
            <!-- 注册表单 -->
            <el-form ref="formRef" size="large" autocomplete="off" v-if="isRegister" :model="registerData" :rules="rules">
                <el-form-item>
                    <h1>注册</h1>
                </el-form-item>
                <el-form-item prop="username">
                    <el-input :prefix-icon="User" placeholder="请输入用户名" v-model="registerData.username"></el-input>
                </el-form-item>
                <el-form-item prop="nickname">
                    <el-input :prefix-icon="ElementPlus" placeholder="请输入昵称" v-model="registerData.nickname"></el-input>
                </el-form-item>
                <el-form-item prop="password">
                    <el-input :prefix-icon="Lock" type="password" placeholder="请输入密码" v-model="registerData.password"></el-input>
                </el-form-item>
                <el-form-item prop="rePassword">
                    <el-input :prefix-icon="Lock" type="password" placeholder="请确认密码" v-model="registerData.rePassword"></el-input>
                </el-form-item>
                <el-form-item prop="email">
                    <el-input :prefix-icon="Message" placeholder="请输入邮箱（选填）" v-model="registerData.email"></el-input>
                </el-form-item>
                <!-- 注册按钮 -->
                <el-form-item>
                    <el-button class="button" type="primary" auto-insert-space @click="register">
                        注册
                    </el-button>
                </el-form-item>
                <el-form-item class="flex">
                    <el-link type="info" :underline="false" @click="isRegister = false; clearRegisterData()">
                        ← 返回
                    </el-link>
                </el-form-item>
            </el-form>
            <!-- 登录表单 -->
            <el-form ref="formRef" size="large" autocomplete="off" v-else :model="loginData" :rules="rules">
                <el-form-item>
                    <h1>登录</h1>
                </el-form-item>
                <el-form-item prop="username">
                    <el-input :prefix-icon="User" placeholder="请输入用户名" v-model="loginData.username"></el-input>
                </el-form-item>
                <el-form-item prop="password">
                    <el-input name="password" :prefix-icon="Lock" type="password" placeholder="请输入密码" v-model="loginData.password"></el-input>
                </el-form-item>
                <el-form-item class="flex">
                    <div class="flex">
<!--                        管理员登录入口-->
                        <a>我是管理员</a>
                        <el-link type="primary" :underline="false" @click="ElMessage.success('祝你今天有个好心情')">忘记密码？</el-link>
                    </div>
                </el-form-item>
                <!-- 登录按钮 -->
                <el-form-item>
                    <el-button class="button" type="primary" auto-insert-space @click="login">登录</el-button>
                </el-form-item>
                <el-form-item class="flex">
                    <el-link type="info" :underline="false" @click="isRegister = true; clearLoginData()">
                        注册 →
                    </el-link>
                </el-form-item>
            </el-form>
        </el-col>
    </el-row>
</template>

<style lang="scss" scoped>

.logo {
    margin: 0 auto;
    width: 50px;
}

.el-text {
    margin: 0 auto;
}
.login-page {
    height: 100vh;
    background-color: #fff;
    color: black;

    .bg {
        background: url('@/assets/images/login_bg2.jpg') no-repeat center / contain;
        border-radius: 0 20px 20px 0;
    }

    .form {
        display: flex;
        flex-direction: column;
        justify-content: center;
        user-select: none;

        .title {
            font-size: 16px;
            font-weight: bold;
            color: #b1191a;
            margin: 10px 0;
        }

        .button {
            width: 100%;
        }

        .flex {
            width: 100%;
            display: flex;
            justify-content: space-between;
        }
    }
}
</style>